package org.aplombh.java.utils.multiThread.juc.pcp;

public class ProducerConsumer_Monitor {

    public static void main(java.lang.String[] args) {
        SynContainer synContainer = new SynContainer();

        new Producer(synContainer).start();
        new Consumer(synContainer).start();
    }

}

class Producer extends Thread {
    SynContainer synContainer;

    public Producer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Produce the " + i + "th roast chicken.");
            synContainer.produce(new Chicken(i));
        }
    }
}

class Consumer extends Thread {
    SynContainer synContainer;

    public Consumer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Buy the " + i + "th roast chicken.");
            Chicken consume = synContainer.consume();
            System.out.println("Eating the " + consume.id + "th roast chicken.");
        }
    }
}

class Chicken {
    int id;

    public Chicken() {
    }

    public Chicken(int id) {
        this.id = id;
    }
}

class SynContainer {
    Chicken[] chickens = new Chicken[10];
    int count = 0;

    public synchronized void produce(Chicken chicken)  {
        if (count == chickens.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        chickens[count++] = chicken;

        this.notifyAll();
    }

    public synchronized Chicken consume()  {
        if (count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        this.notifyAll();

        return chickens[--count];
    }
}